<template>
  <div class="compensation-management-panel">
    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <template #icon>
            <IconifyIcon icon="ant-design:rollback-outlined" />
          </template>
          创建补偿
        </a-button>
        <a-button @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
      </a-space>

      <a-space>
        <a-input-search
          :value="searchKeyword"
          placeholder="搜索补偿记录"
          style="width: 200px"
          @search="handleSearch"
        />
        <a-select
          :value="filterStatus"
          placeholder="补偿状态"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部状态</a-select-option>
          <a-select-option
            v-for="status in compensationStatuses"
            :key="status.value"
            :value="status.value"
          >
            {{ status.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 补偿记录列表 -->
    <a-table
      :columns="columns"
      :data-source="compensations"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusLabel(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'strategy'">
          <a-tag :color="getStrategyColor(record.strategy)">
            {{ getStrategyLabel(record.strategy) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-button
              v-if="record.status === 'PENDING'"
              type="link"
              size="small"
              @click="handleTrigger(record.id)"
            >
              触发
            </a-button>
            <a-button
              v-if="record.status === 'RUNNING'"
              type="link"
              size="small"
              @click="handleCancel(record.id)"
            >
              取消
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 补偿详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="补偿详情"
      width="800px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="补偿ID">{{
          selectedCompensation?.id
        }}</a-descriptions-item>
        <a-descriptions-item label="关联执行">{{
          selectedCompensation?.executionId
        }}</a-descriptions-item>
        <a-descriptions-item label="补偿状态">
          <a-tag :color="getStatusColor(selectedCompensation?.status)">
            {{ getStatusLabel(selectedCompensation?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="补偿策略">
          <a-tag :color="getStrategyColor(selectedCompensation?.strategy)">
            {{ getStrategyLabel(selectedCompensation?.strategy) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="触发时间">{{
          selectedCompensation?.triggerTime
        }}</a-descriptions-item>
        <a-descriptions-item label="完成时间">{{
          selectedCompensation?.completionTime || '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="补偿原因">{{
          selectedCompensation?.reason
        }}</a-descriptions-item>
        <a-descriptions-item label="重试次数">{{
          selectedCompensation?.retryCount || 0
        }}</a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-tabs>
        <a-tab-pane key="logs" tab="补偿日志">
          <a-timeline>
            <a-timeline-item
              v-for="log in selectedCompensation?.logs || []"
              :key="log.id"
              :color="getLogColor(log.level)"
            >
              <p>{{ log.message }}</p>
              <p style="color: #999; font-size: 12px">{{ log.timestamp }}</p>
            </a-timeline-item>
          </a-timeline>
        </a-tab-pane>

        <a-tab-pane key="actions" tab="补偿动作">
          <a-list>
            <a-list-item
              v-for="action in selectedCompensation?.actions || []"
              :key="action.id"
            >
              <a-list-item-meta>
                <template #title>{{ action.name }}</template>
                <template #description>{{ action.description }}</template>
              </a-list-item-meta>
              <template #actions>
                <a-tag :color="getActionStatusColor(action.status)">
                  {{ getActionStatusLabel(action.status) }}
                </a-tag>
              </template>
            </a-list-item>
          </a-list>
        </a-tab-pane>

        <a-tab-pane key="result" tab="补偿结果">
          <pre>{{ JSON.stringify(selectedCompensation?.result, null, 2) }}</pre>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'compensation-triggered': [compensationId: string];
  'compensation-cancelled': [compensationId: string];
}>();

// 响应式数据
const loading = ref(false);
const compensations = ref<any[]>([]);
const searchKeyword = ref('');
const filterStatus = ref('');
const detailModalVisible = ref(false);
const selectedCompensation = ref<any>(null);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 补偿状态选项
const compensationStatuses = computed(() => [
  { value: 'PENDING', label: '等待中' },
  { value: 'RUNNING', label: '执行中' },
  { value: 'SUCCESS', label: '成功' },
  { value: 'FAILED', label: '失败' },
  { value: 'CANCELLED', label: '已取消' },
]);

// 表格列定义
const columns = [
  {
    title: '补偿ID',
    dataIndex: 'id',
    key: 'id',
    width: 120,
  },
  {
    title: '关联执行',
    dataIndex: 'executionId',
    key: 'executionId',
    width: 120,
  },
  {
    title: '补偿状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
  {
    title: '补偿策略',
    dataIndex: 'strategy',
    key: 'strategy',
    width: 120,
  },
  {
    title: '触发时间',
    dataIndex: 'triggerTime',
    key: 'triggerTime',
    width: 180,
    customRender: ({ text }: { text: string }) =>
      new Date(text).toLocaleString(),
  },
  {
    title: '补偿原因',
    dataIndex: 'reason',
    key: 'reason',
    width: 200,
  },
  {
    title: '重试次数',
    dataIndex: 'retryCount',
    key: 'retryCount',
    width: 100,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 'comp-001',
        executionId: 'exec-003',
        status: 'SUCCESS',
        strategy: 'ROLLBACK',
        triggerTime: new Date(Date.now() - 870000).toISOString(),
        completionTime: new Date(Date.now() - 840000).toISOString(),
        reason: '资源配置失败，需要回滚',
        retryCount: 0,
        logs: [
          {
            id: '1',
            level: 'INFO',
            message: '开始执行补偿操作',
            timestamp: '2024-01-01 09:45:30',
          },
          {
            id: '2',
            level: 'INFO',
            message: '回滚配置成功',
            timestamp: '2024-01-01 09:46:00',
          },
        ],
        actions: [
          {
            id: '1',
            name: '回滚配置',
            description: '将资源配置回滚到上一个版本',
            status: 'SUCCESS',
          },
          {
            id: '2',
            name: '清理临时文件',
            description: '清理配置过程中产生的临时文件',
            status: 'SUCCESS',
          },
        ],
        result: { success: true, message: '补偿操作成功完成' },
      },
      {
        id: 'comp-002',
        executionId: 'exec-004',
        status: 'PENDING',
        strategy: 'RETRY',
        triggerTime: new Date(Date.now() - 300000).toISOString(),
        reason: '网络超时，等待重试',
        retryCount: 2,
        logs: [
          {
            id: '1',
            level: 'WARN',
            message: '网络连接超时',
            timestamp: '2024-01-01 10:00:00',
          },
          {
            id: '2',
            level: 'INFO',
            message: '等待重试...',
            timestamp: '2024-01-01 10:00:30',
          },
        ],
        actions: [
          {
            id: '1',
            name: '重试连接',
            description: '重新尝试网络连接',
            status: 'PENDING',
          },
        ],
        result: null,
      },
      {
        id: 'comp-003',
        executionId: 'exec-005',
        status: 'RUNNING',
        strategy: 'COMPENSATE',
        triggerTime: new Date(Date.now() - 60000).toISOString(),
        reason: '数据同步失败，执行补偿',
        retryCount: 0,
        logs: [
          {
            id: '1',
            level: 'INFO',
            message: '开始数据补偿',
            timestamp: '2024-01-01 10:05:00',
          },
          {
            id: '2',
            level: 'INFO',
            message: '正在同步数据...',
            timestamp: '2024-01-01 10:05:30',
          },
        ],
        actions: [
          {
            id: '1',
            name: '数据同步',
            description: '同步数据到目标系统',
            status: 'RUNNING',
          },
          {
            id: '2',
            name: '验证数据',
            description: '验证数据同步结果',
            status: 'PENDING',
          },
        ],
        result: null,
      },
    ];

    compensations.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    message.error('加载补偿记录失败');
    console.error('加载补偿记录失败:', error);
  } finally {
    loading.value = false;
  }
};

const refreshData = () => {
  loadData();
};

const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

const handleFilter = () => {
  pagination.current = 1;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

const showCreateModal = () => {
  message.info('创建补偿功能开发中...');
};

const showDetailModal = (compensation: any) => {
  selectedCompensation.value = compensation;
  detailModalVisible.value = true;
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedCompensation.value = null;
};

const handleTrigger = async (id: string) => {
  try {
    message.success('触发补偿成功');
    emit('compensation-triggered', id);
    loadData();
  } catch (error) {
    message.error('触发补偿失败');
    console.error('触发补偿失败:', error);
  }
};

const handleCancel = async (id: string) => {
  try {
    message.success('取消补偿成功');
    emit('compensation-cancelled', id);
    loadData();
  } catch (error) {
    message.error('取消补偿失败');
    console.error('取消补偿失败:', error);
  }
};

const getStatusLabel = (status: string) => {
  const found = compensationStatuses.value.find((s) => s.value === status);
  return found ? found.label : status;foundfound.labelfoundfound.label
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'default',
    RUNNING: 'processing',
    SUCCESS: 'success',
    FAILED: 'error',
    CANCELLED: 'warning',
  };
  return colorMap[status] || 'default';
};

const getStrategyLabel = (strategy: string) => {
  const labelMap: Record<string, string> = {
    ROLLBACK: '回滚',
    RETRY: '重试',
    COMPENSATE: '补偿',
    IGNORE: '忽略',
  };
  return labelMap[strategy] || strategy;
};

const getStrategyColor = (strategy: string) => {
  const colorMap: Record<string, string> = {
    ROLLBACK: 'red',
    RETRY: 'orange',
    COMPENSATE: 'blue',
    IGNORE: 'default',
  };
  return colorMap[strategy] || 'default';
};

const getActionStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    PENDING: '等待中',
    RUNNING: '执行中',
    SUCCESS: '成功',
    FAILED: '失败',
  };
  return labelMap[status] || status;
};

const getActionStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'default',
    RUNNING: 'processing',
    SUCCESS: 'success',
    FAILED: 'error',
  };
  return colorMap[status] || 'default';
};

const getLogColor = (level: string) => {
  const colorMap: Record<string, string> = {
    INFO: 'blue',
    WARN: 'orange',
    ERROR: 'red',
    DEBUG: 'default',
  };
  return colorMap[level] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.compensation-management-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  pre {
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 300px;
    overflow-y: auto;
  }
}
</style>
